package transform;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Description: TODO QQ1667847363
 * @author: xiao kun tai
 * @date:2021/11/3 10:08
 */
public class Transform1_Base {
    public static void main(String[] args)  throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        String inputPath ="src/main/resources/sensor.txt";

        DataStream<String> inputStream = env.readTextFile(inputPath);

        //map  (line.length)
        DataStream<Integer> mapStream =inputStream.map(new MapFunction<String, Integer>() {
            @Override
            public Integer map(String s) throws Exception {
                return s.length();
            }
        });
        mapStream.print("map");

        //flatmap,按逗号分字段(word1,ward2)
        DataStream<String> flatMapStream =inputStream.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> collector) throws Exception {
                String[] fields =value.split(",");
                for (String field : fields) {
                    collector.collect(field);
                }
            }
        });


        DataStream<Tuple2<String,Integer>> mapStream1 =inputStream.map(new MapFunction<String, Tuple2<String,Integer>>() {
            @Override
            public Tuple2<String,Integer> map(String s) throws Exception {
                return new Tuple2<String,Integer>(s,s.length());
            }
        });

        flatMapStream.print("flatmap");

        //filter 筛选sensor_1开头的id对应的数据
        DataStream<String> filterStream =inputStream.filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String s) throws Exception {
                return s.startsWith("sensor_1");
            }
        });
        filterStream.print("filter");
        env.execute("");



    }
}
